﻿using Cognex.VisionPro;
using Cognex.VisionPro.Blob;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro.ToolBlock;

using HalconDotNet;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace 使用halcon读取DXF赋值给VisionPro的Blob工具
{
    public partial class Main_Form : Form
    {
        private string DxfPath = string.Empty;
        private HObject ho_DxfContours, ho_UnionContours, ho_ObjectSelected = null;
        private HTuple hv_Col = new HTuple();
        private HTuple hv_DxfStatus = new HTuple(), hv_Number = new HTuple();
        private HTuple hv_i = new HTuple(), hv_Length = new HTuple(), hv_Row = new HTuple();
        private HTuple HV_Row = new HTuple(), HV_Col = new HTuple();
        private int index;
        private string[] itemdata = new string[3];
        private CogBlobTool mCogBlobTool;
        private CogImageFileTool mCogImageFileTool;
        private ICogImage mCogImg;
        private CogPolygon mCogPolygon = new CogPolygon();
        private CogToolBlock mCogToolBlock;

        /// <summary>
        /// Dxf数据分析显示
        /// </summary>
        /// <param name="row"></param>
        /// <param name="col"></param>
        /// <param name="Row"></param>
        /// <param name="Col"></param>
        private double P = 0;

        private List<string> PicFile = new List<string>();
        private List<double> Row, Col;
        private string VppPath = string.Empty;

        public Main_Form()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)  //获取DXF文件
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
            {
                DxfPath = GetDXF(op.FileName);
            }
            label2.Text = "DXF的文件路径为：" + DxfPath;
        }

        //string vppPath=Application.StartupPath+@"\Vpp.vpp"';
        private void button2_Click(object sender, EventArgs e)      //加载Vpp
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("视觉处理模板未加载");
                return;
            }
            VppPath = op.FileName;
            mCogToolBlock = (CogToolBlock)CogSerializer.LoadObjectFromFile(VppPath);
        }

        private void button3_Click(object sender, EventArgs e)  //清空数据
        {
            listView1.Items.Clear();
            Row.Clear();
            Col.Clear();
        }

        private void button4_Click(object sender, EventArgs e)      //分析DXF并显示数据
        {
            GetDxfDatas(DxfPath, out HV_Row, out HV_Col);
            int l = HV_Row.TupleLength();
            SeparateData(HV_Row, HV_Col, out Row, out Col);
        }

        private void button5_Click(object sender, EventArgs e)      //写入DXF数据
        {
            try
            {
                mCogBlobTool = mCogToolBlock.Tools[textBox1.Text] as CogBlobTool;
                mCogPolygon.GraphicDOFEnableBase = CogGraphicDOFConstants.All;
                mCogPolygon.Interactive = true;

                while (mCogPolygon.NumVertices != 0)
                {
                    mCogPolygon.RemoveVertex(0);
                }
                mCogBlobTool.Region = mCogPolygon;
                for (int i = 0; i < Row.Count; i++)
                {
                    mCogPolygon.AddVertex(Row[i], Col[i], -1);
                }
                mCogBlobTool.Region = mCogPolygon;
                mCogBlobTool.Run();
                mCogToolBlock.Run();
                File.Delete(VppPath);
                //CogSerializer.SaveObjectToFile(mCogToolBlock, VppPath);
                CogSerializer.SaveObjectToFile(mCogToolBlock, @"D:\11.vpp");
                if (MessageBox.Show("请确认，确认后，软件关闭", "", MessageBoxButtons.OK) == DialogResult.OK) ;
                {
                    Environment.Exit(0);
                }
            }
            catch (Exception ex) { ex.ToString(); }
        }

        /// <summary>
        /// 遍历获取图像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)  //载入图像
        {
            if (index == -1)
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    DirectoryInfo dir = new DirectoryInfo(fbd.SelectedPath);
                    PicFile.Clear();
                    foreach (FileInfo item in dir.GetFiles())
                    {
                        if ((item.Extension == ".jpg" || item.Extension == ".bmp" || item.Extension == ".jpeg" || item.Extension == ".png"))
                        {
                            PicFile.Add(item.FullName);
                        }
                    }
                }
            }
            index++;
            if (index > PicFile.Count)
            {
                index = -1;
                return;
            }
            try
            {
                try
                {
                    mCogImageFileTool.Operator.Open(PicFile[index].ToString(), CogImageFileModeConstants.Read);
                    mCogImageFileTool.Run();
                    mCogImg = null;
                    mCogImg = mCogImageFileTool.OutputImage;
                    cogRecordDisplay1.StaticGraphics.Clear();
                    cogRecordDisplay1.InteractiveGraphics.Clear();
                    cogRecordDisplay1.Image = null;
                    cogRecordDisplay1.Image = mCogImg;
                    cogRecordDisplay1.Fit(true);
                }
                catch { }
            }
            catch { }
        }

        private void button7_Click(object sender, EventArgs e)          //测量
        {
            mCogToolBlock.Inputs[0].Value = mCogImg;
            mCogToolBlock.Run();
            cogRecordDisplay1.StaticGraphics.Clear();
            cogRecordDisplay1.InteractiveGraphics.Clear();
            cogRecordDisplay1.Record = mCogToolBlock.CreateLastRunRecord();

            cogRecordDisplay1.Image = mCogImg;
            cogRecordDisplay1.Fit(true);
        }

        /// <summary>
        /// 获取Dxf文件
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        private string GetDXF(string _path)
        {
            FileInfo info = new FileInfo(_path);
            if (info.Extension != ".dxf" && info.Extension != ".DXF")
            {
                MessageBox.Show("加载文件错误，请检查文件类型");
                return null;
            }
            return _path;
        }

        /// <summary>
        /// 获取Dxf的数据
        /// </summary>
        /// <param name="file"></param>
        /// <param name="HV_Row"></param>
        /// <param name="HV_Col"></param>
        private void GetDxfDatas(string file, out HTuple HV_Row, out HTuple HV_Col)
        {
            hv_Row = 0;
            hv_Col = 0;
            HV_Row = 0;
            HV_Col = 0;
            try
            {
                HOperatorSet.GenEmptyObj(out ho_DxfContours);
                HOperatorSet.GenEmptyObj(out ho_UnionContours);
                HOperatorSet.GenEmptyObj(out ho_ObjectSelected);
                ho_DxfContours.Dispose(); hv_DxfStatus.Dispose();
                HOperatorSet.ReadContourXldDxf(out ho_DxfContours, file,
                    new HTuple(), new HTuple(), out hv_DxfStatus);
                ho_UnionContours.Dispose();
                HOperatorSet.UnionAdjacentContoursXld(ho_DxfContours, out ho_UnionContours, 10,
                    1, "attr_keep");
                hv_Number.Dispose();
                HOperatorSet.CountObj(ho_UnionContours, out hv_Number);
                HTuple end_val3 = hv_Number;
                HTuple step_val3 = 1;

                for (hv_i = 1; hv_i.Continue(end_val3, step_val3); hv_i = hv_i.TupleAdd(step_val3))
                {
                    ho_ObjectSelected.Dispose();
                    HOperatorSet.SelectObj(ho_UnionContours, out ho_ObjectSelected, 1);
                    hv_Length.Dispose();
                    HOperatorSet.LengthXld(ho_ObjectSelected, out hv_Length);
                    hv_Row.Dispose(); hv_Col.Dispose();
                    HOperatorSet.GetContourXld(ho_ObjectSelected, out hv_Row, out hv_Col);
                    HV_Row.Append(hv_Row.ToOArr());
                    HV_Col.Append(hv_Col.ToDArr());
                    hv_Col.Dispose();
                    hv_Row.Dispose();
                }
                List<object> temp = HV_Row.ToOArr().ToList();
                temp.RemoveAt(0);
                HV_Row = temp.ToArray();
                List<object> temp2 = HV_Col.ToOArr().ToList();
                temp2.RemoveAt(0);
                HV_Col = temp2.ToArray();
            }
            catch
            {
            }
            ho_DxfContours.Dispose();
            ho_UnionContours.Dispose();
            ho_ObjectSelected.Dispose();
            hv_DxfStatus.Dispose();
            hv_Number.Dispose();
            hv_i.Dispose();
            hv_Length.Dispose();
        }

        private void Main_Form_Load(object sender, EventArgs e)
        {
            listView1.Columns.Clear();
            listView1.Columns.Add("序号", 60, HorizontalAlignment.Center);
            listView1.Columns.Add("行数据", 100, HorizontalAlignment.Center);
            listView1.Columns.Add("列数据", 100, HorizontalAlignment.Center);
            listView1.AllowDrop = false;
            listView1.AllowColumnReorder = false;
            mCogImageFileTool = new CogImageFileTool();
            mCogImg = null;
            mCogToolBlock = new CogToolBlock();
            mCogBlobTool = new CogBlobTool();
            index = -1;
        }

        private void OnDisplay(int num, double row0, double col0)
        {
            this.BeginInvoke(new Action<int, double, double>((int i, double row, double col) =>
            {
                listView1.Items.Add(new ListViewItem(new String[] { (i).ToString(), row.ToString("f3"), col.ToString("f3") }));
            }), num, row0, col0);
        }

        private void SeparateData(HTuple row, HTuple col, out List<double> Row, out List<double> Col)
        {
            if (!double.TryParse(txtCa.Text, out P))
            {
                MessageBox.Show("未输入比例系数，请检查");
                P = 0;
                Row = null;
                Col = null;
                return;
            }
            Row = new List<double>(row.Length);
            Col = new List<double>(col.Length);
            if (row.Length <= 0 && col.Length <= 0)
            {
                MessageBox.Show("数据错误");
                Row = null;
                Col = null;
                return;
            }
            Row.Clear();
            Col.Clear();
            foreach (var r in row.ToOArr())
            {
                Row.Add((double)r / P);
            }
            foreach (var c in col.ToOArr())
            {
                Col.Add((double)c / P);
            }
            if (Row.Count != Col.Count)
            {
                MessageBox.Show("获取的数据错误");
                return;
            }
            ShowData(Row, Col);
            col.Dispose();
            row.Dispose();
        }

        private void ShowData(List<double> row, List<double> col)
        {
            for (int i = 0; i < row.Count; i++)
            {
                OnDisplay(i, row[i], col[i]);
            }
        }
    }
}